package com.cooper.mediadb.online;

import java.io.IOException;
import java.net.MalformedURLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import android.util.Log;

import com.cooper.scraper.DownloadException;
import com.cooper.scraper.HttpDownload;

public class AnalyzeDefault extends AnalyzeVideo {

	private static final String TO_FAST_REQUEST_STR = "提示：对不起，两次解析间隔时间太短，请5秒钟后刷新页面重试。";

	private static final String FORMAT_CANNT_ANALYZE = "该清晰度视频需要安装迅雷看看高清播放组件才能播放，无法解析";

	private boolean redirectUrl;

	public AnalyzeDefault(String url, String format,
			boolean redirectUrl) {
		super(url, format);
		this.redirectUrl = redirectUrl;
	}

	List<String> findMediaSrc(String page) throws MalformedURLException,
			IOException {
		List<String> result = new ArrayList<String>();
		Pattern p = Pattern
				.compile("<td\\s*align=left\\s*class=\"mn STYLE4\">\\s*<br>下载地址：(([^<]*<[^>]*>)+?)\\s*<tr\\s*valgin=[^>]*>\\s*<td\\s*align=left\\s*class=\"mn STYLE4\">\\s*<br>花费时间");
		Matcher m = p.matcher(page);
		if (m.find()) {
			String pageSrc = m.group(1);
			Pattern p2 = Pattern
					.compile("<a href=\"(.+?)\" target=\"_blank\"[^>]*>[^<]*</a>");
			Matcher m2 = p2.matcher(pageSrc);
			while (m2.find()) {
				Log.d("analyzedefault", "" + m2.group(1));
				result.add(HttpDownload.getInstance().getRedirectUrl(m2.group(1),
						new HashMap<String, String>(0)));
			}
		}
		return result;

	}

	@Override
	public List<String> analyzeVideo() throws DownloadException,
			IOException {
		if (redirectUrl) {
			url = HttpDownload.getInstance().getRedirectUrl(url);
		}
		String page = null;
		String flvcdAnalyzeUrl = "http://www.flvcd.com/parse.php?kw=" + url
				+ "&format=" + format;
		while (true) {
			page = HttpDownload.getInstance().downloadPage(flvcdAnalyzeUrl, "gb2312", false,
					new HashMap<String, String>(0));
			if (Thread.currentThread().isInterrupted())
				break;

			if (page.contains(TO_FAST_REQUEST_STR)) {
				try {
					Thread.sleep(5000);
				} catch (InterruptedException e1) {
					page = null;
					break;
				}
			} else if (page.contains(FORMAT_CANNT_ANALYZE)) {
				flvcdAnalyzeUrl = "http://www.flvcd.com/parse.php?kw=" + url;
			} else
				break;
		}
		List<String> result;
		if (!Thread.currentThread().isInterrupted() && page != null) {
			result = findMediaSrc(page);
		} else {
			result = new ArrayList<String>(0);
		}
		return result;

	}

}
